﻿namespace TestApp.Client
{
    using System;
    using System.Diagnostics.Contracts;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Interactivity;
    using Contracts;
    using JetBrains.Annotations;

    public sealed class DataGridColumnsBehavior : Behavior<DataGrid>
    {
        [CanBeNull] public DataTemplate CellTemplate { get; set; }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += AssociatedObjectOnLoaded;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Loaded -= AssociatedObjectOnLoaded;
            base.OnDetaching();
        }

        private void AssociatedObjectOnLoaded([NotNull] object sender, [NotNull] RoutedEventArgs routedEventArgs)
        {
            Contract.Requires<ArgumentNullException>(sender != null);
            Contract.Requires<ArgumentNullException>(routedEventArgs != null);
            for (var index = 0; index < EntityDto.ParameterCount; index++)
            {

                AssociatedObject.Columns.Add(
                    new CustomDataGridTemplateColumn
                    {
                        CellTemplate = CellTemplate,
                        Header = (index + 1).ToString(CultureInfo.CurrentUICulture),
                        Binding = new Binding(string.Format("Params[{0}]", index))
                    });
            }
        }

        private sealed class CustomDataGridTemplateColumn : DataGridBoundColumn
        {
            [CanBeNull] public DataTemplate CellTemplate { get; set; }

            protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
            {
                var presenter = new ContentPresenter { ContentTemplate = CellTemplate };
                presenter.SetBinding(ContentPresenter.ContentProperty, Binding);
                return presenter;
            }

            protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
            {
                throw new NotImplementedException();
            }
        }
    }
}
